<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import Chart from 'chart.js/auto'

const teacherNum = ref(0)
const deptNum = ref(0)
const TeacherAvgAge = ref(0)
const TitleAtr = ref([])
const DepTeacherAtr = ref([])
const deptChart = ref(null)
const titleChart = ref(null)


// 获取部门职称统计数据
const DashData = async () => {
  try {
    // 获取部门职称统计
    const dashResponse = await axios.get('/api/dash/header')

    const result_data = dashResponse.data.data || {};


    // 设置基本数据
    teacherNum.value = result_data.teacherNum || 0;
    deptNum.value = result_data.deptNum || 0;
    TeacherAvgAge.value = result_data.teacherAvgAge || 0;

    // 处理职称数据
    let temp_TitleAtr = {}; // 初始化为空对象
    if (Array.isArray(result_data.titleResult)) {
      result_data.titleResult.forEach(item => {
        if (item && item.title && item.count !== undefined) {
          temp_TitleAtr[item.title] = item.count;
        }
      });
    }
    else{
      console.log(result_data)
      throw new Error("错的离谱了")
    }
    TitleAtr.value = new Map(Object.entries(temp_TitleAtr));

    // 处理部门数据
    let temp_DepTeacherAtr = {}; // 初始化为空对象
    if (Array.isArray(result_data.deptResult)) {
      result_data.deptResult.forEach(item => {
        if (item && item.department && item.count !== undefined) {
          temp_DepTeacherAtr[item.department] = item.count;
        }
      });
    }
    DepTeacherAtr.value = new Map(Object.entries(temp_DepTeacherAtr));

  } catch (error) {
    console.error('获取统计数据失败:', error)
    alert('获取统计数据失败，请稍后重试')
  }
}

const initializeCharts = () => {
  const deptChartData = {
    labels: [...DepTeacherAtr.value.keys()],
    datasets: [{
      label: '部门人数',
      data: [...DepTeacherAtr.value.values()],
      backgroundColor: 'rgba(75, 192, 192, 0.5)',
      borderColor: 'rgba(75, 192, 192, 1)',
      borderWidth: 1
    }]
  }
  const titleChartData = {
    labels: [...TitleAtr.value.keys()],
    datasets: [{
      label: '职称分布',
      data: [...TitleAtr.value.values()],
      backgroundColor: [
        'rgba(255, 99, 132, 0.5)',
        'rgba(54, 162, 235, 0.5)',
        'rgba(255, 206, 86, 0.5)',
        'rgba(75, 192, 192, 0.5)',
        'rgba(153, 102, 255, 0.5)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)'
      ],
      borderWidth: 1
    }]
  }
  const depctx = document.getElementById('departmentChart')
  const titlectx = document.getElementById('titleDistributionChart')
  deptChart.value = new Chart(depctx, {
    type: 'bar',
    data: deptChartData,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: '部门人数统计'
        }
      }
    }
  })
  titleChart.value = new Chart(titlectx, {
    type: 'pie',
    data: titleChartData,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: '教职工职称分布'
        }
      }
    }
  })

}


onMounted(async () => {
  await DashData();
  initializeCharts();
});

</script>

<template>
  <div class="container mx-auto">
    <section class="mb-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">仪表盘</h2>
      </div>
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <div class="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start">
            <div>
              <p class="text-gray-500 text-sm mb-1">教职工总数</p>
              <h3 class="text-2xl font-bold text-gray-800" id="total-staff">{{ teacherNum }}</h3>
            </div>
            <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center">
              <i class="fa fa-users text-primary text-xl"></i>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start">
            <div>
              <p class="text-gray-500 text-sm mb-1">部门数量</p>
              <h3 class="text-2xl font-bold text-gray-800" id="total-departments">{{ deptNum }}</h3>
            </div>
            <div class="w-12 h-12 rounded-full bg-secondary/10 flex items-center justify-center">
              <i class="fa fa-sitemap text-secondary text-xl"></i>
            </div>
          </div>
        </div>


        <div class="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow">
          <div class="flex justify-between items-start">
            <div>
              <p class="text-gray-500 text-sm mb-1">教职工平均年龄</p>
              <h3 class="text-2xl font-bold text-gray-800" id="average-age">{{ TeacherAvgAge }}</h3>
            </div>
            <div class="w-12 h-12 rounded-full bg-warning/10 flex items-center justify-center">
              <i class="fa fa-calendar text-warning text-xl"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <div class="bg-white rounded-lg p-6 shadow-sm lg:col-span-2">
          <div class="flex justify-between items-center mb-4">
            <h3 class="font-semibold text-gray-800">教职工职称分布</h3>
          </div>
          <div class="h-80">
            <canvas id="titleDistributionChart"></canvas>
          </div>
        </div>

        <div class="bg-white rounded-lg p-6 shadow-sm">
          <div class="flex justify-between items-center mb-4">
            <h3 class="font-semibold text-gray-800">部门人数统计</h3>
          </div>
          <div class="h-80">
            <canvas id="departmentChart"></canvas>
          </div>
        </div>
      </div>
    </section>

  </div>



</template>

<style scoped>

</style>


